package be.rivendale.renderer.mk2.remote;

import be.rivendale.renderer.mk2.LoadBalancer;
import be.rivendale.renderer.mk2.data.Queue;
import be.rivendale.renderer.mk2.data.Segment;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class NodeDetectorThread extends Thread {
    private LoadBalancer loadBalancer;
    private Queue<Segment> resultQueue;

    public NodeDetectorThread(LoadBalancer loadBalancer, Queue<Segment> resultQueue) {
        this.loadBalancer = loadBalancer;
        this.resultQueue = resultQueue;
        start();
    }

    @Override
    public void run() {
        try {
            System.out.print("Listening for slaves... ");
            ServerSocket serverSocket = new ServerSocket(1507);
            Socket socket = serverSocket.accept();
            System.out.println("Found.");
            Receiver receiver = new Receiver(new SocketStreamer(socket), resultQueue);
            loadBalancer.addProducer(receiver);
        } catch (IOException exception) {
            throw new RuntimeException("Unable to listen for slaves", exception);
        }
    }
}
